package com.glela.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.glela.api.model.AlipayAppKeyInfo;
import com.glela.api.model.PayAppKeyInfo;
import com.glela.api.pay.alipay.component.Alipay;
import com.glela.api.pay.wechat.component.WeChat;
import com.glela.api.pay.wechat.component.impl.WeChat0Impl;
import com.glela.api.pay.wechat.component.impl.WeChatImpl;
import com.glela.api.pay.yeepay.component.YeePay;
import com.glela.api.pay.yeepay.model.YeePayBaseRequest;
import com.glela.api.pay.yeepay.model.YeePayRefundModel;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.util.OrderUtil;
import com.glela.order.model.OrderObject;
import com.glela.order.service.OrderService;

@Controller
@RequestMapping("refund")
public class RefundController {
	private static Logger logger = LoggerFactory.getLogger(RefundController.class);
			
	@Resource(name = "orderService2")
	private OrderService orderService2;
	
	@Autowired
	private YeePay yeePay;
	
	@Autowired
	private List<WeChat> weChatList;
	
	@Autowired
	private Alipay alipay;
	
	/**
	 * 易宝退邮费
	 * @param yeePayBaseRequest
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/partRefund", method = RequestMethod.POST, consumes = "application/json")
	public void yeePayRefundPostage(@RequestBody YeePayBaseRequest yeePayBaseRequest, HttpServletRequest request) {
		try {
			/*if (ParameterUtils.validParams(yeePayBaseRequest.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}*/
			
			// String orderSnStr = "P148954866251370001,P148954866386898703,P148954886519812101,P148954888172230506,P148954899276339710,P148954899771973406,P148954950360339715,P148954951950173107,P148954958830391517,P148954963000295719,P148954992668532011,P148954994594206828,P148955051934182046,P148955056439486338,P148955065908615252,P148955071325610340,P148955071527624021,P148955079013205855,P148955116070897750,P148955133955122180,P148955146653015458,P148955147669663701,P148955155011024861,P148955216218182908,P148955258704062514,P148955260431474416,P148955265157610407,P148955279756457026,P148955285025438629,P148955291871757016,P148955348934968845,P148955354196259547,P148955360886800250,P148955390842628916,P148955469029440170,P148955477644090474,P148955499617304047,P148955506685352729,P148955509103815980,P148955514160546631,P148955520257728753,P148955524972836484,P148955534003043186,P148955545861633191,P148955555484767938,P148955574690117198,P148955576589062602,P148955583190663504,P148955593924524208,P148955595799305411,P148955595827834740,P148955596818567113,P148955603853147215,P148955606065371286,P148955609232922928,P148955621184587197,P148955637828967104,P148955655255030646,P148955664155081249,P148955684762173152,P148955688185220154,P148955704116258420,P148955723660603970,P148955728331832065,P148955735887035728,P148955738062981472,P148955740258790674,P148955756623931736,P148955768948142083,P148955776288522287,P148955788143677693,P148955788672337043,P148955791020087145,P148955794628451447,P148955795237700197,P148955804055150703,P148955809759049905,P148955817191115911,P148955818459716015,P148955820221199418,P148955824272769624,P148955831829059727,P148955836841107032,P148955839803854981,P148955856797529198,P148955871716108852,P148955875350353257,P148955880742603761,P148955899604710772,P148955916124905023,P148955935923505383,P148955941972840836,P148955942675635386,P148955955099996590,P148955958863272896,P148955959459020040,P148955961838934901,P148955962436714203,P148955963272441405,P148955967888059343,P148955979463945717,P148955985859842252,P148955988927596657,P148955989602443201,P148955996205570970,P148956006360249076,P148956012310809483,P148956036567199216";
			String orderSnStr = "P148954866386898703,P148954886519812101,P148954888172230506,P148954899276339710,P148954899771973406,P148954950360339715,P148954951950173107,P148954958830391517,P148954963000295719,P148954992668532011,P148954994594206828,P148955051934182046,P148955056439486338,P148955065908615252,P148955071325610340,P148955071527624021,P148955079013205855,P148955116070897750,P148955133955122180,P148955146653015458,P148955147669663701,P148955155011024861,P148955216218182908,P148955258704062514,P148955260431474416,P148955265157610407,P148955279756457026,P148955285025438629,P148955291871757016,P148955348934968845,P148955354196259547,P148955360886800250,P148955390842628916,P148955469029440170,P148955477644090474,P148955499617304047,P148955506685352729,P148955509103815980,P148955514160546631,P148955520257728753,P148955524972836484,P148955534003043186,P148955545861633191,P148955555484767938,P148955574690117198,P148955576589062602,P148955583190663504,P148955593924524208,P148955595799305411,P148955595827834740,P148955596818567113,P148955603853147215,P148955606065371286,P148955609232922928,P148955621184587197,P148955637828967104,P148955655255030646,P148955664155081249,P148955684762173152,P148955688185220154,P148955704116258420,P148955723660603970,P148955728331832065,P148955735887035728,P148955738062981472,P148955740258790674,P148955756623931736,P148955768948142083,P148955776288522287,P148955788143677693,P148955788672337043,P148955791020087145,P148955794628451447,P148955795237700197,P148955804055150703,P148955809759049905,P148955817191115911,P148955818459716015,P148955820221199418,P148955824272769624,P148955831829059727,P148955836841107032,P148955839803854981,P148955856797529198,P148955871716108852,P148955875350353257,P148955880742603761,P148955899604710772,P148955916124905023,P148955935923505383,P148955941972840836,P148955942675635386,P148955955099996590,P148955958863272896,P148955959459020040,P148955961838934901,P148955962436714203,P148955963272441405,P148955967888059343,P148955979463945717,P148955985859842252,P148955988927596657,P148955989602443201,P148955996205570970,P148956006360249076,P148956012310809483,P148956036567199216";
			
			String [] orderSnList = orderSnStr.split(",");
			
			String result = "";
			String refundFeeNo = "";
			for (String orderSn : orderSnList) {
				OrderObject orderObject = getOrderService().selectOrderObjectByOrderSn(orderSn);
				if (orderObject == null) continue;
				String refundSn = "FA" + OrderUtil.getOrderSn();
				
				if (orderObject.getPayType() > 3) {
					result = yeePayPartRefund(orderObject, refundSn);
					JSONObject resultJson = JSONObject.parseObject(result);
					String refundCode = resultJson.getString("code");
					if (refundCode.equals("1")) {
						refundFeeNo = resultJson.getString("refundexternalid");
					} else {
						logger.error("--------->YeePay Refund Faild Response:" + result);
					}
				}
				
				if (orderObject.getPayType() == 1 || orderObject.getPayType() == 3) {
					Map<String, Object> outmap = weChatPartRefund(orderObject, refundSn);
					if ("SUCCESS".equals(outmap.get("return_code"))) {
						refundFeeNo = outmap.get("refund_id").toString(); //微信的退款号
					}
				}
				
				if (orderObject.getPayType() == 2) {
					AlipayAppKeyInfo alipayAppKeyInfo=getOrderService().getAlipayAppKeyInfo();
					AlipayTradeRefundResponse response = alipay.alipayRefund(alipayAppKeyInfo, orderObject.getOrderSn(),
							orderObject.getPayId(), orderObject.getFreight().longValue(), refundSn);
					if (response.isSuccess()) {
						if(response.getFundChange().equals("Y")){
							refundFeeNo = "支付宝无退款流水";
						} else {
							logger.info(response.getBody());
						}
					}
				}
				getOrderService().updateOrderObjectFreightNo(orderObject.getId(), refundFeeNo);
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
		}
	}
	
	private String yeePayPartRefund(OrderObject orderObject,String refundSn) {
		// TODO Auto-generated method stub
		// 构建请求易宝的参数
		YeePayRefundModel model = new YeePayRefundModel();
		String divide = getOrderService().selectSettlementAccount(orderObject.getId());
		model.setOrderrequestid(orderObject.getOrderSn()); // 请求退款的单号
		model.setAmount((orderObject.getFreight().doubleValue()/100) + "");
		model.setConfirm("1"); // 确认退款 固定值1
		model.setDivideinfo(divide + ":AMOUNT"+(orderObject.getFreight().doubleValue()/100)); // 不填写则默认从主账户上扣款
		model.setRequestid(refundSn); // 退款单号
		model.setMemo("System Auto Refund Postage."); // 商户备注
		String result = yeePay.yeePayRefund(model);
		logger.info("------->YeePay Response Args:" + result);
		return result;
	}

	private Map<String, Object> weChatPartRefund(OrderObject orderObject,String refundSn) throws IOException {
		// TODO Auto-generated method stub
		Map<String, Object> outmap = null;
		PayAppKeyInfo payAppKeyInfo = getOrderService().getPayAppKeyInfo(orderObject.getPayType());
		outmap = getWeChat(orderObject.getPayType()).weChaPayRefund(payAppKeyInfo, orderObject.getOrderSn(),
				orderObject.getTotalFee(), orderObject.getFreight(),
				refundSn, orderObject.getPayId());
		return outmap;
	}

	private OrderService getOrderService() {
		return orderService2;
	}
	
	private WeChat getWeChat(int payType) {
		WeChat theWeChat=null;
		if(payType==PayTypeEnum.T1.getCode())
		{
			for (WeChat weChat : weChatList) {
				if(weChat instanceof WeChat0Impl)
				{
					theWeChat= weChat;
				}
			}
		}
		else if(payType==PayTypeEnum.T3.getCode())
		{
			for (WeChat weChat : weChatList) {
				if(weChat instanceof WeChatImpl)
				{
					theWeChat= weChat;
				}
			}
		}
		else
		{
			theWeChat=weChatList.get(0);
		}
		return theWeChat;
	}
}
